package org.cnbi.web.controller;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.cnbi.entity.User;
import org.cnbi.service.ISystemService;
import org.cnbi.utils.tools.ActionConstants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.web.controller.base.BaseController;
import org.cnbi.web.system.manager.ClientManager;
import org.cnbi.web.system.pojo.base.Client;
import org.cnbi.web.utils.ContextHolderUtils;
import org.cnbi.web.utils.IpUtil;
import org.cnbi.web.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController extends BaseController {

	//private static final Log logger = LogFactory.getLog(LoginController.class);

	@Autowired
	private ISystemService systemService;

	/**
	 * 用户登录
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, User user) {
		User bean = systemService.login(getSqlByKey(ActionConstants.MANAGE + GlobalConstants.LOGIN_USER), user);
		if (null != bean) {
			byte[] salt = PasswordUtil.getStaticSalt();
			String plaintext = PasswordUtil.decrypt(bean.getPassword(), user.getPassword(), salt);
			if (null != plaintext && plaintext.equals(user.getUsername())){
				HttpSession session = request.getSession();
				session.setAttribute(GlobalConstants.LOGIN_USER, bean);
				/**
				 * 添加到在线用户管理里
				 */
				
				Client client = new Client();
				client.setIp(IpUtil.getIpAddr(request));
				client.setLoginTime(new Date());
				client.setUser(user);
				ClientManager.getInstance().addClinet(session.getId(), client);
				/**
				 * 添加到登陆日志
				 */
				systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("用户【" + user.getUsername()+ "】登录成功！", GlobalConstants.Log_Type_LOGIN, GlobalConstants.Log_Leavel_INFO));
				/**
				 * 加载用户权限
				 */
				setRights();
                String nav = getCurrentNav(request);
				return "redirect:/" + nav;
			}
		}
		request.setAttribute("errorMsg", "用户名或密码错误！");
		return "forward:/";
	}
	/**
	 * 用户安全退出
	 */
	@RequestMapping("/loginOut")
	public String loginOut() {
		HttpSession session = ContextHolderUtils.getSession();
	    User user = ContextHolderUtils.getCurrentUser();
	    if(null !=user){
		 systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("用户" + user.getUsername() + "已退出", GlobalConstants.Log_Type_EXIT, GlobalConstants.Log_Leavel_INFO));
	    }
		 ClientManager.getInstance().removeClinet(session.getId());
		return "redirect:/";
	}

	/**
	 * 登录用户权限加载
	 */
	private void setRights() {

	}

}
